package com.addzero.jimmer.baseentity

import cn.hutool.core.util.ObjUtil
import com.addzero.infra.LoginUtil
import org.babyfish.jimmer.DraftObjects
import org.babyfish.jimmer.kt.isLoaded
import org.babyfish.jimmer.sql.DraftInterceptor
import org.springframework.stereotype.Component
import java.time.LocalDateTime

@Component
class BaseEntityDraftInterceptor : DraftInterceptor<BaseEntity, BaseEntityDraft> {

    override fun beforeSave(draft: BaseEntityDraft, original: BaseEntity?) {
        val loginUserId = LoginUtil.getLoginUserId()
        val now = LocalDateTime.now()


        if (isLoaded(draft, BaseEntityDraft::id) && ObjUtil.isEmpty(draft.id)) {
            DraftObjects.unload(draft, "id")
        }

        if (!isLoaded(draft, BaseEntityDraft::updateTime) || draft.updateTime == null) {
            draft.updateTime = now
        }

        if (!isLoaded(draft, BaseEntityDraft::updateBy) || draft.updateBy == null) {
            draft.updateBy {
                id = loginUserId
            }
        }

        if (original === null) {
            if (!isLoaded(draft, BaseEntityDraft::createTime)) {
                draft.createTime = now
            }

            if (!isLoaded(draft, BaseEntityDraft::createBy) || draft.createBy == null) {
                draft.createBy {
                    id = loginUserId
                }
            }
        }
    }
}
